<template>
  <div style="width: 100%; height: 100%">
    <ol-map ref="mapRef" style="width: 100%; height: 100%">
      <ol-view
        ref="view"
        :center="center"
        :rotation="rotation"
        :zoom="zoom"
        :maxZoom="maxZoom"
        :projection="projection"
        @change:center="centerChanged"
        @change:resolution="resolutionChanged"
        @change:rotation="rotationChanged"
      />

      <ol-tile-layer>
        <ol-source-xyz
          :url="`tiles/{z}/{x}/{y}.jpg`"
          :attributions="attributions"
        />
      </ol-tile-layer>

      <ol-vector-layer :visible="tubeVisible">
        <ol-source-vector>
          <ol-feature
            v-for="(item, index) in tubeSourceRef"
            :key="index"
            :properties="{ id: item.id, properties: item.properties }"
          >
            <ol-geom-multi-line-string
              :coordinates="item.geometry.coordinates"
            ></ol-geom-multi-line-string>
            <ol-style>
              <ol-style-stroke
                color="#ff0000"
                :width="tubeWidth"
              ></ol-style-stroke>
              <ol-style-text
                v-if="tubeTextVisible"
                :text="item.properties.TYMC"
                :offsetY="18"
                :font="'16px 黑体,sans-serif'"
                :fill="[3, 5, 3]"
                :placement="'line'"
                textAlign="center"
                textBaseline="middle"
              />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="wellVisible">
        <ol-source-vector>
          <ol-feature
            v-for="(item, index) in wellSourceRef"
            :key="index"
            :properties="{ id: item.id, properties: item.properties }"
          >
            <ol-geom-point :coordinates="item.geometry.coordinates" />
            <ol-style>
              <ol-style-circle :radius="wellRadius">
                <ol-style-fill color="#ff0000" />
                <ol-style-stroke :width="wellStrokeWidth" color="#ff0000" />
              </ol-style-circle>
              <ol-style-text
                :text="item.properties.井名"
                :offsetY="18"
                :font="'16px 黑体,sans-serif'"
                :fill="[3, 5, 3]"
              />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-vector-layer :visible="stationVisible">
        <ol-source-vector>
          <ol-feature
            v-for="(item, index) in stationSourceRef"
            :key="index"
            :properties="{ id: item.id, properties: item.properties }"
          >
            <ol-geom-point :coordinates="item.geometry.coordinates" />
            <ol-style>
              <ol-style-icon
                v-if="item.properties.站库名称.indexOf('卸油台') > -1"
                :scale="stationScale"
                :src="PngXieYouTai"
              />
              <ol-style-icon
                v-else-if="item.properties.站类型.indexOf('拉油点') > -1"
                :scale="stationScale * 0.5"
                :src="PngLaYouDian"
              />
              <ol-style-icon
                v-else-if="item.properties.站类型.indexOf('计量站') > -1"
                :scale="stationScale"
                :src="PngJiLiangZhan"
              />
              <ol-style-icon
                v-else-if="item.properties.站类型.indexOf('阀室') > -1"
                :scale="stationScale"
                :src="PngFashi"
              />
              <ol-style-text
                :text="item.properties.站库名称"
                :offsetY="20"
                :font="'15px 黑体,sans-serif'"
              />
            </ol-style>
          </ol-feature>
        </ol-source-vector>
      </ol-vector-layer>

      <ol-rotate-control></ol-rotate-control>
      <ol-fullscreen-control></ol-fullscreen-control>
      <ol-mouseposition-control />
    </ol-map>
    <TModal />
    <WModal />
    <MSModal />
  </div>
</template>

<script setup lang="ts">
import { watch, onMounted, ref, onBeforeMount } from 'vue';
import Map from 'ol/Map';

import type { FeatureLike } from 'ol/Feature';

import { useVbenModal } from '@vben/common-ui';
import TubeModal from './modal/tubeModal.vue';
import WellModal from './modal/wellModal.vue';
import MeasuringStationModal from './modal/measuringStationModal.vue';
import TankModal from './modal/tankModal.vue';

import PngXieYouTai from '#/assets/gis/卸油台L.png';
import PngLaYouDian from '#/assets/gis/拉油点N.png';
import PngJiLiangZhan from '#/assets/gis/计量站.png';
import PngFashi from '#/assets/gis/油集输管线阀池L.png';

import { getStationsApi, getWellsApi, getTubesApi } from '#/api/gis';

const attributions =
  '© <a href="https://www.ckxgzxa.top" target="_blank"><bold>CKXGZXA</bold></a> 版权所有.';
const center = ref([86.069, 46.148]);
const projection = ref('EPSG:4326');
const zoom = ref(14);
const maxZoom = ref(19);
const rotation = ref(0);

const currentCenter = ref(center.value);
const currentZoom = ref(zoom.value);
const currentRotation = ref(rotation.value);
const currentResolution = ref(0);

const stationSourceRef = ref();
const stationVisible = ref(false);
const stationScale = ref(1);

const tubeSourceRef = ref();
const tubeVisible = ref(true);
const tubeWidth = ref(3);
const tubeTextVisible = ref(false);

const wellSourceRef = ref();
const wellStrokeWidth = ref(0);
const wellRadius = ref(0);
const wellVisible = ref(false);

watch(currentZoom, (zoom) => {
  if (zoom >= 17) {
    tubeTextVisible.value = true;
  } else {
    tubeTextVisible.value = false;
  }

  if (zoom < 16) {
    wellVisible.value = false;
    stationVisible.value = false;
  } else {
    // 随zoom线性增长, 速率越来越慢
    wellVisible.value = true;
    stationVisible.value = true;

    wellStrokeWidth.value = 5 * (zoom - 15) + 1;
    tubeWidth.value = zoom * 0.3;
    stationScale.value = zoom * 0.03;
  }
});

const mapRef = ref<{ map: Map }>();

function resolutionChanged(event: {
  target: { getResolution: () => number; getZoom: () => number };
}) {
  currentResolution.value = event.target.getResolution();
  currentZoom.value = event.target.getZoom();
}
function centerChanged(event: { target: { getCenter: () => number[] } }) {
  currentCenter.value = event.target.getCenter();
}
function rotationChanged(event: { target: { getRotation: () => number } }) {
  currentRotation.value = event.target.getRotation();
}

const [TModal, TModalApi] = useVbenModal({
  connectedComponent: TubeModal,
  title: 'Tube Modal',
});

const [WModal, WModalApi] = useVbenModal({
  connectedComponent: WellModal,
  title: 'Well Modal',
});

const [MSModal, MSModalApi] = useVbenModal({
  connectedComponent: MeasuringStationModal,
  title: 'Measuring Station Modal',
});

const [TkModal, TkModalApi] = useVbenModal({
  connectedComponent: TankModal,
  title: 'Tank Modal',
});

function openTubeModal(data: any) {
  TModalApi.setState({
    title: data.properties.TYMC,
    draggable: true,
  });
  TModalApi.setData(data.properties);
  TModalApi.open();
}

function openWellModal(data: any) {
  WModalApi.setState({
    title: data.properties.井名,
    draggable: true,
  });
  WModalApi.setData(data.properties);
  WModalApi.open();
}

function openMeasuringStationModal(data: any) {
  MSModalApi.setState({
    title: data.properties.站库名称,
    draggable: true,
  });
  MSModalApi.setData(data.properties);
  MSModalApi.open();
}

function openTankModal(data: any) {
  TkModalApi.setState({
    title: data.properties.站库名称,
    draggable: true,
  });
  TkModalApi.setData(data.properties);
  TkModalApi.open();
}

async function fetchData() {
  try {
    // 获取集输数据
    var res = await getTubesApi();
    tubeSourceRef.value = res.data.features;
    console.log('tubeSourceRef', tubeSourceRef.value);

    // 获取生产井数据
    res = await getWellsApi();
    wellSourceRef.value = res.data.features;
    console.log('wellSourceRef', wellSourceRef.value);

    // 获取站库数据
    res = await getStationsApi();
    stationSourceRef.value = res.data.features;
    console.log('stationSourceRef', stationSourceRef.value);
  } catch (error) {
    // 捕获并处理错误
    console.error('Error fetching data:', error);
  }
}

onBeforeMount(() => {
  fetchData();
});

onMounted(() => {
  const map: Map = mapRef.value?.map!;
  map.on('click', (event) => {
    // 打印出当前位置要素信息
    map.forEachFeatureAtPixel(event.pixel, (feature: FeatureLike) => {
      console.log(feature);
      var featureId: number | string = feature.getProperties().id!;

      // 判断featureId中是否含有集输, 如有将featureId设为0, 含有井设为1
      if (featureId.toString().indexOf('集输') > -1) {
        featureId = 0;
      } else if (featureId.toString().indexOf('井') > -1) {
        featureId = 1;
      } else if (featureId.toString().indexOf('站库') > -1) {
        featureId = 2;
      } else if (featureId.toString().indexOf('阀池') > -1) {
        featureId = 3;
      } else if (featureId.toString().indexOf('计量站') > -1) {
        featureId = 4;
      } else if (featureId.toString().indexOf('拉油点') > -1) {
        featureId = 5;
      } else {
        featureId = -1;
      }

      switch (featureId) {
        case 0:
          openTubeModal(feature.getProperties());
          break;
        case 1:
          openWellModal(feature.getProperties());
          break;
        case 2:
          break;
        case 3:
          break;
        case 4:
          openMeasuringStationModal(feature.getProperties());
          break;
        case 5:
          openTankModal(feature.getProperties());
          break;
        default:
          break;
      }
    });
  });
});
</script>
